package com.cxf.windex.rest;

import com.alibaba.fastjson.JSON;
import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.rest.BaseRestController;
import com.cxf.windex.base.util.EncryptUtil;
import com.cxf.windex.base.util.IdUtil;
import com.cxf.windex.base.util.WxUtil;
import com.cxf.windex.biz.CityInfoBiz;
import com.cxf.windex.biz.JsTechBiz;
import com.cxf.windex.biz.JsUserBiz;
import com.cxf.windex.entity.JsTech;
import com.cxf.windex.entity.JsUser;
import com.cxf.windex.enums.StatusEnum;
import com.cxf.windex.enums.TypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenxf
 * @date 3/16/2018
 * @description
 */
@Api(tags = {"小程序 - 用户接口"})
@Controller
@RequestMapping("user/user")
public class UserController extends
        BaseRestController<JsUserBiz, JsUser> {

  @Autowired
  private JsTechBiz jsTechBiz;

  @Value("${weixin.appid}")
  private String appid;

  @Value("${weixin.secret}")
  private String secret;

  private static final String  SUCCESS="SUCCESS";
  @Autowired
  private CityInfoBiz cityInfoBiz;


  @RequestMapping(value = "/test", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse test() {
     String username=this.getCurrentUserName();
      return new ObjectRestResponse().rel(false).msg("用户不存在"+username);

  }

  @RequestMapping(value = "/fetch", method = RequestMethod.GET)
  @ResponseBody
  public void fetch(){

    cityInfoBiz.fetchDetail();
  }

  @ApiOperation(value = "后台登陆", notes = "登陆返回TOKEN")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "username", value = "用户名", required = true, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query", dataType = "String")
  })
  @RequestMapping(value = "/adminLogin", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse adminLogin(String username, String password) {
    Map<String, Object> resultMap = new HashMap<String, Object>(4);
    JsUser queryEntity = new JsUser();
    queryEntity.setUsername(username);
    JsUser entity = baseBiz.selectOne(queryEntity);
    if (entity == null) {
      return new ObjectRestResponse().rel(false).msg("用户不存在");
    }
    if (!EncryptUtil.decrypt(entity.getPassword()).equals(password)) {
      return new ObjectRestResponse().rel(false).msg("密码不正确");
    }
    resultMap.put("token",
        this.setCurrentUserName(entity));
    return new ObjectRestResponse().rel(true).msg("登陆成功").result(resultMap);
  }

  @ApiOperation(value="登陆", notes="登陆返回TOKEN")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "code", value = "登陆code", required = false, paramType="query", dataType = "String"),
      @ApiImplicitParam(name = "openid", value = "微信openid", required = false,  paramType="query",dataType = "String")
  })
  @RequestMapping(value = "/login", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse login(String code,String openid){
    Map<String,Object> resultMap=new HashMap<String, Object>(4);
    if(StringUtils.isBlank(openid)){
      //获取openId
      resultMap.putAll(WxUtil.getOpenId(appid,secret,code));
      if(resultMap.get("errcode")!=null && StringUtils.isNotBlank(resultMap.get("errcode").toString())){
        return  new ObjectRestResponse().rel(false).msg("获取openid失败，错误码："+resultMap.get("errcode"));
      }
      openid=resultMap.get("openid").toString();
    }
    JsUser entity=new JsUser();
    entity.setOpenid(openid);
    entity= baseBiz.selectOne(entity);
    if(entity==null){
      return  new ObjectRestResponse().rel(false).msg("用户不存在").result(resultMap);
    }

    resultMap.put("token", this.setCurrentUserName(entity));
    JsTech queryEntity=new JsTech();
    queryEntity.setUserid(entity.getId());
    JsTech tech=jsTechBiz.selectOne(queryEntity);
    if(tech==null){
      resultMap.put("jsId","0");
    }else{
      resultMap.put("jsId",tech.getId());
    }
    return  new ObjectRestResponse().rel(true).msg("登陆成功").result(resultMap);
  }

  @ApiOperation(value="解密手机号码", notes="解密手机号码")
  @RequestMapping(value = "/phone", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse decryptPhone(@RequestBody Map<String,String> paramMap){
    String encryptedData=paramMap.get("encryptedData"), iv=paramMap.get("iv"), sessionKey=paramMap.get("sessionKey");
    if(StringUtils.isBlank(encryptedData)||StringUtils.isBlank(iv)||StringUtils.isBlank(sessionKey)){
      return  new ObjectRestResponse().rel(false).msg("请传入encryptedData和IV和sessionKey");
    }
    try {
      Map<String,Object> resultMap=(Map<String, Object>)JSON.parseObject(EncryptUtil.decrypt(sessionKey,iv,encryptedData),Map.class);
      logger.debug("resultmap={}",resultMap);
      String id=this.getCurrentUserId();
      if(id!=null &&StringUtils.isNotBlank(id)){
        JsUser user=new JsUser();
        user.setId(id);
        user.setMobile(resultMap.get("phoneNumber").toString());
        user.setUsername(resultMap.get("phoneNumber").toString());
        baseBiz.updateSelectiveById(user);
      }


      return  new ObjectRestResponse().rel(true).msg("解密完成").result(resultMap);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return  new ObjectRestResponse().rel(false).msg("sessionKey失效");
  }

  @ApiOperation(value="注册", notes="注册返回TOKEN")
  @RequestMapping(value = "/register", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse register(@RequestBody JsUser entity){
    entity.setId(new IdUtil(5,1).nextId()+"");
    entity.setStatus(StatusEnum.NORMAL.getKey());
    entity.setType(TypeEnum.GUEST.getKey());
    if(StringUtils.isNotBlank(entity.getInviter())){
      entity.setCrtUser(entity.getInviter());
    }
    Map<String,Object> resultMap=new HashMap<String, Object>(4);
    baseBiz.insert(entity);
    resultMap.put("token", this.setCurrentUserName(entity));
    resultMap.put("openid",entity.getOpenid());
    return  new ObjectRestResponse().rel(true).msg("注册成功").result(resultMap);
  }

  @ApiOperation(value="支付结果", notes="返回支付结果")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "return_msg", value = "返回信息", required = false,  paramType="query",dataType = "String"),
      @ApiImplicitParam(name = "result_code", value = "支付结果", required = false,  paramType="query",dataType = "String"),
      @ApiImplicitParam(name = "openid", value = "微信openid", required = false,  paramType="query",dataType = "String")
  })
  @RequestMapping(value = "/pay", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse pay(String return_msg,String result_code,String openid){
    if(result_code==null||!result_code.equals(SUCCESS)){
      return  new ObjectRestResponse().rel(false).msg(return_msg);
    }

    JsUser entity=new JsUser();
    entity.setOpenid(openid);
    JsUser user= baseBiz.selectOne(entity);
    if(user==null){
      return  new ObjectRestResponse().rel(false).msg("用户不存在");
    }
    entity.setId(user.getId());
    entity.setType(TypeEnum.VIP.getKey());
    entity.setStatus(StatusEnum.PAYSUCCESS.getKey());
    baseBiz.updateSelectiveById(entity);
    return  new ObjectRestResponse().rel(true).msg("支付成功");
  }

  @RequestMapping(value = "/pwd", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse pwd(String password,String newPassword,String newPassword2){
    if(StringUtils.isBlank(password)){
      return  new ObjectRestResponse().rel(false).msg("密码不能为空");
    }

    if(StringUtils.isBlank(newPassword)){
      return  new ObjectRestResponse().rel(false).msg("新密码不能为空");
    }

    if(StringUtils.isBlank(newPassword2)){
      return  new ObjectRestResponse().rel(false).msg("重复新密码不能为空");
    }

    if(!newPassword.equals(newPassword2)){
      return  new ObjectRestResponse().rel(false).msg("重复新密码与新密码不相同");
    }
    String username=this.getCurrentUserName();
    if(StringUtils.isBlank(username)){
      return  new ObjectRestResponse().rel(false).msg("当前用户不存在");
    }
    JsUser user=baseBiz.selectOne(new JsUser(username));
    if(user==null){
      return  new ObjectRestResponse().rel(false).msg("用户不存在");
    }
    if(!EncryptUtil.decrypt(user.getPassword()).equals(password)){
      return  new ObjectRestResponse().rel(false).msg("密码不正确");
    }
    JsUser pwduser=new JsUser();
    pwduser.setId(user.getId());
    pwduser.setPassword(EncryptUtil.encrypt(newPassword));
    baseBiz.updateSelectiveById(pwduser);
    return  new ObjectRestResponse().rel(true).msg("修改成功");
  }
}
